package io.renren.modules.app.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.commons.io.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.RandomUtil;
import io.renren.common.annotation.SysLog;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.app.entity.WxKafKaMsg;
import io.renren.modules.app.entity.ibps.Employee;
import io.renren.modules.app.service.IEmployeeService;
import io.renren.modules.app.temp.SpringDataPageable;
import io.renren.modules.app.utils.ZimgClient;
import io.renren.modules.app.utils.ZimgClient.ZimgResult;
import io.renren.modules.job.task.TaskPdf;
import jodd.io.FileUtil;
import jodd.typeconverter.Converter;

@RestController
@RequestMapping("/app/user")
public class UserController {
	@Autowired
	IEmployeeService userService;

	private Converter converter = Converter.get();

	@Value("${pafBasePath}")
	String pdfBasePath;

	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;

	@RequestMapping("/msg")
	public void msg() {
		WxKafKaMsg wxKafKaMsg = new WxKafKaMsg();
		wxKafKaMsg.setAppId("");
//		JSONObject.toJSONString(object);
		this.kafkaTemplate.send("test", "测试下");
	}

	/**
	 * 上传文件
	 */
	@SysLog("上传签名")
	@RequestMapping("/upload")
	@RequiresPermissions("app:pdf:list")
	public R upload(@RequestParam("file") MultipartFile multipartFile, @RequestParam Map<String, Object> params) throws Exception {
		if (multipartFile.isEmpty()) {
			throw new RRException("上传文件不能为空");
		}
		Long id = Convert.toLong(params.get("id"));
		Optional<Employee> findById = userService.findById(id);
		if (!findById.isPresent()) {
			return R.error("没有找到该用户!");
		}
		String qm = "qianming";
		String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));

		File forder = new File(StrFormatter.format("{}/{}/{}", pdfBasePath, qm, id));
		if (!FileUtil.isExistingFolder(forder)) {
			FileUtil.mkdir(forder);
		}
		String jpgName = RandomUtil.randomString(8);
		File fileJpgAbs = new File(StrFormatter.format("{}/{}/{}/{}{}", pdfBasePath, qm, id, jpgName, suffix));

		FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), fileJpgAbs);
		// 图片改为图片服务器
		ZimgClient zimg = new ZimgClient(TaskPdf.picServer, TaskPdf.picServer);
		ZimgResult uploadImg = zimg.uploadImg(fileJpgAbs.getAbsolutePath());
		if (uploadImg.isRet()) {
			Employee user = findById.get();
			user.setQm(uploadImg.getInfo().getMd5());
			userService.save(user);
			return R.ok("签名上传成功!").put("url", user.getQm());
		}
		return R.error("签名上传失败");
	}

	@SysLog("查看pdf")
	@GetMapping("/info/{id}")
	@RequiresPermissions("app:pdf:list")
	public R info(@PathVariable("id") Long id) {
		Optional<Employee> findById = userService.findById(id);
		if (!findById.isPresent()) {
			return R.error("没有找到该id");
		}
		Employee user = findById.get();
		user.setQm(user.getQm());
		return R.ok().put("config", user).put("url", TaskPdf.picServer);
	}

	@GetMapping("/list")
	@RequiresPermissions("app:pdf:list")
	public R list(@RequestParam Map<String, Object> params) {
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "updateTime"));

		SpringDataPageable pageable = this.getDataPageable(params, orders);
//		userService.findAll(pageable);

		Page<Employee> page = userService.findAll(pageable);

		PageUtils pageUtils = new PageUtils(page.getContent(), converter.toIntValue(page.getTotalElements()), page.getPageable().getPageSize(), page.getPageable().getPageNumber());
		return R.ok().put("page", pageUtils).put("url", TaskPdf.picServer);
	}

	private SpringDataPageable getDataPageable(Map<String, Object> params, List<Order> orders) {
		SpringDataPageable pageable = new SpringDataPageable();
		pageable.setPagesize(converter.toIntValue(params.get("limit")));
		pageable.setPagenumber(converter.toIntValue(params.get("page")));
		pageable.setSort(Sort.by(orders));
		return pageable;
	}
}
